package com.example.smartmedicalsystem.service;

import com.example.smartmedicalsystem.entity.Message;
import com.example.smartmedicalsystem.entity.User;
import com.example.smartmedicalsystem.repository.MessageRepository;
import com.example.smartmedicalsystem.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@RequiredArgsConstructor
public class MessageService {
    private final MessageRepository messageRepository;
    private final UserRepository userRepository;

    @Transactional
    public Message sendMessage(Long senderId, Long receiverId, String content) {
        User sender = senderId != null ?
                userRepository.findById(senderId)
                        .orElseThrow(() -> new RuntimeException("发送者不存在")) :
                null;
        User receiver = userRepository.findById(receiverId)
                .orElseThrow(() -> new RuntimeException("接收者不存在"));

        Message message = new Message();
        message.setSender(sender);
        message.setReceiver(receiver);
        message.setContent(content);
        return messageRepository.save(message);
    }

    public List<Message> getUnreadMessages(Long userId) {
        return messageRepository.findByReceiverIdAndIsReadFalse(userId);
    }

    public List<Message> getAllMessages(Long userId) {
        return messageRepository.findByReceiverIdOrderByCreatedAtDesc(userId);
    }

    @Transactional
    public void markAsRead(Long messageId) {
        Message message = messageRepository.findById(messageId)
                .orElseThrow(() -> new RuntimeException("消息不存在"));
        message.setRead(true);
        messageRepository.save(message);
    }
}